<script setup lang="ts">
import { useChatStore } from "@s/chat";

import { storeToRefs } from "pinia";
import { computed, nextTick, ref } from "vue";

const inputModalValue = ref("");
const searchVal = ref("");
const pay_url = "/order/money?productType=3";

const group_id = ref<number>(0);
const chat = useChatStore();
const {
  showcanvas,
  chatList,
  siteloading,
  activeIndex,
  activeGroupId,
  userinfo,
} = storeToRefs(chat);

const clickQuestion = (item: any) => {
  let id = item.id;
  let index = chatList.value.findIndex((it) => it.id === id);
  chat.changeGroup(index as number);
};

const openEditModal = (type = "add") => {
  let title = "新增会话";
  if (type === "add") {
    title = "新增会话";
  } else if (type == "edit") {
    title = "编辑会话";
  }

  ElMessageBox.prompt("请输入你的会话名称", title, {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputValue: inputModalValue,
    beforeClose: async (action: any, instance: any, done: any) => {
      if (action === "confirm") {
        let value = (inputModalValue.value || "").trim();
        if (!value) {
          return ElMessage({
            type: "warning",
            message: `请输入会话名称`,
          });
        }
        if (value.length > 50) {
          return ElMessage({
            type: "warning",
            message: `会话名称字数不能超过50`,
          });
        }
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "Loading...";
        let res: any;
        if (type === "add") {
          res = await chat.addGroup(value);
        } else {
          res = await chat.editGroup(value, group_id.value);
        }
        let msg = res.msg;

        if (res.code == 1) {
          ElMessage({
            type: "success",
            message: msg,
          });
          done();
        } else {
          ElMessage({
            type: "error",
            message: msg,
          });
          done();
        }
      } else {
        done();
      }
    },
  });
};

const editHandler = (item: any, index: number) => {
  group_id.value = item.id;
  inputModalValue.value = item.name;
  openEditModal("edit");
};

const deleteGroup = async () => {
  let res: any = await chat.deleteGroup(group_id.value);
  if (res.code == 1) {
    ElMessage({
      type: "success",
      message: res.msg,
    });
  } else {
    ElMessage({
      type: "error",
      message: res.msg,
    });
  }
};

const deleteHandler = (item: any, index: number) => {
  group_id.value = item.id;
  ElMessageBox.confirm("是否删除改会话?", "提示", {
    confirmButtonText: "OK",
    cancelButtonText: "取消",
    type: "删除",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        await deleteGroup();
        done();
      } else {
        done();
      }
    },
  });
};

const filterChatList = computed(() => {
  if (searchVal.value) {
    return chatList.value.filter((item: any) =>
      item.name.includes(searchVal.value.trim()),
    );
  } else {
    return chatList.value;
  }
});

// 输入框事件
const searchHandler = (e: Event) => {
  let value = (e?.target as HTMLInputElement)?.value ?? "";
  searchVal.value = value;
};

// 新增会话
const addTask = async () => {
  inputModalValue.value = "";
  openEditModal("add");
};
</script>
<template>
  <nav class="sidebar sidebar-offcanvas" :class="showcanvas ? 'active' : ''">
    <ul class="nav">
      <li class="nav-item s-m20">
        <button class="add s-btn btn btn-gradient-primary font-weight-bold todo-list-add-btn" @click="addTask">
          新建会话
        </button>
      </li>
      <li class="nav-item s-search">
        <div class="search-field d-none d-md-block">
          <form class="d-flex align-items-center h-100" action="#">
            <div class="input-group">
              <div class="input-group-prepend bg-transparent">
                <i class="input-group-text border-0 mdi mdi-magnify"></i>
              </div>
              <input type="text" @input="searchHandler" class="s-ml-10 form-control bg-transparent border-0"
                placeholder="搜索历史记录" />
            </div>
          </form>
        </div>
      </li>
      <div class="s-question" id="question" v-loading="siteloading">
        <template v-for="(item, index) in filterChatList">
          <li @click="clickQuestion(item)" class="nav-item nav-link s-line-2"
            :class="item.id === activeGroupId ? 'active1' : ''">
            <div class="height">
              <div>
                <div class="menu-title title s-ml-10 form-control bg-transparent border-0">
                  {{ item.name }}
                </div>
              </div>
              <div class="hover1">
                <el-icon @click="deleteHandler(item, index)" style="margin-right: 10px">
                  <Delete />
                </el-icon>
                <el-icon @click="editHandler(item, index)">
                  <Edit />
                </el-icon>
                <!-- <i class="mdi mdi-border-color menu-icon s-icon" :id="'edit-' + index"></i> -->
              </div>
            </div>
          </li>
        </template>
      </div>
      <div>
        <div class="userinfo" v-loading="!userinfo" v-if="userinfo">
          <el-avatar :size="40" style="flex-shrink: 0">
            <img src="/static/chat/assets/images/3ea6beec64369c2642b92c6726f1epng.png" />
          </el-avatar>
          <div class="info">
            <div class="username">{{ userinfo?.username }}</div>
            <div class="times">
              赠送余额: {{ userinfo?.receive_money }}
            </div>
            <div class="times">
              付费余额: {{ userinfo?.money }}
              <a class="paytext" :href="pay_url" target="_blank">充值</a>
            </div>
          </div>
        </div>
      </div>
    </ul>
  </nav>
</template>
<style scoped lang="scss">
.nav-item {
  cursor: pointer;

  .menu-title {
    display: flex;
    align-items: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .hover1 {
    display: none;
    align-items: center;
    justify-content: center;
    transform: translateX(-5px) translateY(5px);
  }
}

.s-question {
  height: calc(100vh - 310px);
  overflow-y: auto;
}

.s-question :hover .hover1 {
  display: flex;
}

.userinfo {
  display: flex;
  align-items: center;
  border: 1px solid #731bf7;
  background: #ffffff;
  padding: 10px 20px 10px 10px;
  margin-left: 10px;
  margin-right: 10px;

  .info {
    margin-left: 8px;
    flex: 1;

    .username {
      font-size: 14px;
    }

    .times {
      font-size: 12px;
      color: #444;
      display: flex;
      margin-top: 5px;
      justify-content: space-between;

      .paytext {
        cursor: pointer;
        color: #731bf7;
      }
    }
  }
}
</style>
